package com.syyo.admin.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: wang
 * @date: 2020/12/12 9:10
 * @Description: 发送https请求
 */
@Slf4j
public class MyHttpUtils {

    private static final int MAX_SOKET_TIMEOUT = 8000;
    private static final int MAX_CONNECTION_TIMEOUT = 8000;
    private static final RequestConfig REQCONFIG = RequestConfig.custom().setSocketTimeout(MAX_SOKET_TIMEOUT).setConnectTimeout(MAX_CONNECTION_TIMEOUT).build();


    public static String get(String url) {
        return get(url, null, null);
    }

    public static String get(String url, Map<String, String> params) {
        return get(url, params, null);
    }

    /**
     * get
     *
     * @param url
     * @param
     * @param
     * @return
     */
    public static String get(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(REQCONFIG).build();

        // 添加参数
        StringBuilder full_url = new StringBuilder(url);
        if (params != null && params.size() > 0) {
            full_url.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                full_url.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            // 删除最后一个&
            int end = full_url.lastIndexOf("&");
            full_url.delete(end, end + 1);
        }

        HttpGet get = new HttpGet(full_url.toString());

        // 添加请求头
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                get.setHeader(entry.getKey(), entry.getValue());
            }
        }

        CloseableHttpResponse response = null;
        String result = null;
        String errorMsg;
        try {
            response = httpClient.execute(get);
            HttpEntity resEntity = response.getEntity();
            result = EntityUtils.toString(resEntity);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            errorMsg = e.getMessage();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return errorMsg;
    }

    /**
     * 发送post，json参数
     *
     */
    public static String postJson(String url) {
        return postJson(url, null, null, null);
    }

    /**
     * 发送post，json参数，不带请求头的请求
     *
     */
    public static String postJson(String url, String json) {
        return postJson(url, json, null, null);
    }

    /**
     * 发送post，json参数，不带请求头的请求
     *
     */
    public static String postJson(String url, String json, Map<String, String> headers) {
        return postJson(url, json, headers, null);
    }

    /**
     * 发送post，json，带请求头的请求
     *
     * @param url
     * @param json
     * @param charset
     * @param headers
     * @return
     */
    public static String postJson(String url, String json, Map<String, String> headers, String charset) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(REQCONFIG).build();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String result = null;

        // 添加编号格式
        if (charset == null) {
            charset = "UTF-8";
        }

        // 添加请求头
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Accept", "application/json");

        // 添加消息体
        if (MyStringUtils.isNotEmpty(json)) {
            StringEntity stringEntity = new StringEntity(json, charset);
            httpPost.setEntity(stringEntity);
        }

        String errorMsg;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            result = EntityUtils.toString(resEntity, charset);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            errorMsg = e.getMessage();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return errorMsg;
    }

    /**
     * 发送post，map参数，带请求头的请求
     *
     */
    public static String postMap(String url) {
        return postMap(url, null, null, null);
    }

    /**
     * 发送post，map参数，带请求头的请求
     *
     * @return
     */
    public static String postMap(String url, Map<String, String> map) {
        return postMap(url, map, null, null);
    }

    /**
     * 发送post，map参数，带请求头的请求
     *
     * @return
     */
    public static String postMap(String url, Map<String, String> map, Map<String, String> headers) {
        return postMap(url, map, headers, null);
    }

    /**
     * 发送post，map参数，带请求头的请求
     *
     * @param url
     * @param map
     * @param charset
     * @param headers
     * @return
     */
    public static String postMap(String url, Map<String, String> map, Map<String, String> headers, String charset) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(REQCONFIG).build();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String result = null;
        String errorMsg = "";

        if (charset == null) {
            charset = "utf-8";
        }

        // 添加请求头
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }

        //设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if (map != null && map.size() > 0) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        //  发送请求
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            result = EntityUtils.toString(resEntity, charset);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            errorMsg = e.getMessage();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return errorMsg;
    }
}
